<?php
/**
 * Created by PhpStorm.
 * User: Dmitry
 * Date: 28.02.2015
 * Time: 4:20
 */

class DatabaseProvider {

   var $pdo = null;

    function __construct()
    {
      self::connectDatabase();
    }

    public  function connectDatabase()
    {

        try {

            $this->pdo = new PDO("mysql:host=sql3.freesqldatabase.com;port=3306;dbname=sql369787", 'sql369787', 'iC7*kM6%');

            if($this->pdo != null)
                return true;
            return false;
        }
        catch(PDOException $e) {
            echo $e->getMessage();
            return false;
        }
    }

    /* PREPARE FUNCTIONS FOR INSERT AND UPDATE COMMANDS*/
    public function prepareQuery($query)
    {
        if($query != null)
        {
            $sth = $this->pdo->prepare($query);
            $sth->execute();
        }
    }

    public function prepareQueryA($query, $data)
    {
        if($query != null && data != null)
        {
            $sth = $this->pdo->prepare($query);
            $sth->execute($data);
        }
    }

    public function fetch($query)
    {
        if($query != null)
        {
            $sth = $this->pdo->query($query);
            $sth->setFetchMode(PDO::FETCH_ASSOC);
            return $sth->fetch();
        }
        return null;
    }

    public function query($query)
    {
        try{
            $query = trim($query);
            $sth = $this->pdo->query($query,PDO::FETCH_ASSOC);
            if(!sth)
            {

            }
            $result = null;
            foreach($sth as $row) {
                $result[] = $row;
            }
            return $result != null ? json_encode($result) : null;
        }
        catch(exception $e)
        {
            echo("Exception " . $e);
        }
    }

    public function queryAssoc($query)
    {
        try{
            $query = trim($query);
            $sth = $this->pdo->query($query,PDO::FETCH_ASSOC);
            if(!sth)
            {

            }
            $result = null;
            foreach($sth as $row) {
                $result[] = $row;
            }
            return $result != null ? $result : null;
        }
        catch(exception $e)
        {
            echo("Exception " . $e);
        }
    }


    public function closeConnection()
    {
        $this->pdo = null;
    }



}